package com.zsj.qzt_punch.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zsj.qzt_punch.http.QztHttpRequest;
import com.zsj.qzt_punch.pojo.QztTokenInfo;
import com.zsj.qzt_punch.pojo.UserInfo;
import com.zsj.qzt_punch.service.QztTokenInfoService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;

@Component
@Slf4j
public class GetTokenQzt {


    @Autowired
    QztTokenInfoService qztTokenInfoService;

    static String token = "";

    /**
     * 获取用户信息后返回token值
     * 1天执行一次
     *
     * @return token值
     */
    @Scheduled(fixedDelay = 86400000)
//    @Scheduled(fixedDelay = 10000)
    public void getToken() throws InterruptedException {
        QueryWrapper<QztTokenInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", "郑声军");
        if (qztTokenInfoService.getOne(wrapper) != null) {
            token = qztTokenInfoService.getOne(wrapper).getTokenValue();
        } else {

            token = "备用token";
            token = "改为最新你的token";

        }
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(QztHttpRequest.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        QztHttpRequest request = retrofit.create(QztHttpRequest.class);
        Call<ResponseBody> requestToken = request.getToken(token);
        requestToken.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    log.info("请求发送成功（获取用户信息）");
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create();
                    UserInfo info = new UserInfo();
                    try {
                        if (response.body() != null) {
                            info = gson.fromJson(response.body().string(), UserInfo.class);
                        }
                        if (info != null) {
                            log.info("获取到的token值为:{}", info.getData().getToken());
                            token = info.getData().getToken();
                            QztTokenInfo qztTokenInfo = new QztTokenInfo();
                            qztTokenInfo.setTokenValue(token);
                            qztTokenInfo.setUserName(info.getData().getUserName());
                            UpdateWrapper<QztTokenInfo> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("user_name", "数据库字典名称").set("token_value", token);
                            if (qztTokenInfoService.update(updateWrapper)) {
                                log.info("将token存入数据库成功");
                            } else {
                                log.error("token存入数据库失败");
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                String message = throwable.getMessage();
                log.error(message);
            }
        });
    }
}
